package pl.edu.agh.iosr.gamblingzone.adminpanel.action;

import java.util.Calendar;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

import pl.edu.agh.iosr.gamblingzone.model.MoneyVoucher;
import pl.edu.agh.iosr.gamblingzone.utils.DAOFactory;
import pl.edu.agh.iosr.gamblingzone.utils.HashGenerator;

@Stateful
@Scope(ScopeType.EVENT)
@Name("voucherGenerator")
public class MoneyVoucherGeneratorAction implements MoneyVoucherGenerator {

	@PersistenceContext
	private EntityManager em;

	@In(required = true)
	DAOFactory dao;

	@Logger
	Log log;
	
	private int numberOfVouchers;
	private int validityPeriod;
	private long value;

	@In
	private FacesMessages facesMessages;
	
	@Create
	public void init() {
		numberOfVouchers = 1;
		validityPeriod = 1;
		value = 1;
	}
	
	public void generate() {
		log.info("numberOfVouchers " + numberOfVouchers);
		log.info("value " + value);
		log.info("validityPeriod " + validityPeriod);
		
		String hash = null;
		Calendar validDate = Calendar.getInstance();
		validDate.add(Calendar.DAY_OF_YEAR, validityPeriod);
		
		for(int i = 0; i < numberOfVouchers; i++) {
			MoneyVoucher mv = new MoneyVoucher();
			mv.setActive(Boolean.TRUE);
			mv.setValue(value);
			mv.setExpirationDate(validDate.getTime());
			hash = HashGenerator.generateVoucherHash();
			mv.setVoucherHash(hash);
			em.persist(mv);
			facesMessages.add(hash);
		}
	}

	public int getNumberOfVouchers() {
		log.info(numberOfVouchers);
		return numberOfVouchers;
	}
	
	public void setNumberOfVouchers(int numberOfVouchers) {
		log.info(numberOfVouchers);
		this.numberOfVouchers = numberOfVouchers;
	}
	
	public int getValidityPeriod() {
		return validityPeriod;
	}

	public void setValidityPeriod(int validityPeriod) {
		this.validityPeriod = validityPeriod;
	}

	public long getValue() {
		return value;
	}

	public void setValue(long value) {
		this.value = value;
	}

	@Remove
	public void destroy() {
	}
	
}
